package com.sz.app.oss.api.logistics.order;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.constants.CommCodes;
import com.sz.biz.logistics.constants.ErrorCodes;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.utils.DateUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.biz.logistics.ord.entity.OrdOrderFileTypeEnum;
import com.sz.biz.logistics.ord.entity.OrderStatus;
import com.sz.biz.logistics.ord.service.OrdOrderFileService;
import com.sz.biz.logistics.ord.dto.OrdOderFileTypeDto;
import com.sz.biz.logistics.ord.dto.OrdOrderFileDto;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

/**
 * Function: 订单附件controller
 * Author: yanhong.xiao.<br>
 * Date: 2017-08-08 14:35:00.
 */
@RestController
@RequestMapping("/api/v1/order/files")
@Api(description = " ", tags = "036-004、订单-附件")
public class OrdOrderFileController extends BaseController {
    @Autowired
    private OrdOrderFileService orderFileService;


    @ApiOperation(value = "根据订单的状态，获取订单的附件类型字典数据", httpMethod = "GET",position = 1)
    @RequestMapping(value = "/fileTypes", method = {RequestMethod.GET})
    public ResultDto getOrderFileDicts( @RequestParam OrderStatus orderStatus) {
        OrdOrderFileTypeEnum typeEnum = OrdOrderFileTypeEnum.valueOfEnum(orderStatus.getCode());
        //参数有效性判断
        if (null == typeEnum) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_ILLEGAL, "orderStatus");
        }
        List<OrdOderFileTypeDto> result = orderFileService.queryOrderFileTypes(typeEnum);
        ResultDto resultDto = new ResultDto();
        resultDto.setData(result);
        return resultDto;
    }


    /**
     * 异步校验某个订单下，附件名称的唯一性
     */
    @ApiOperation(value = "校验某个订单下，附件名称的唯一性", notes = "校验附件名称的唯一性,false表示存在，true表示不存在",position = 2)
    @ApiImplicitParams({

            @ApiImplicitParam(name = "orderNo", value = "订单编号,新建订单时不需要", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "fileName", value = "附件名称", dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "/files/name/check", method = {RequestMethod.GET})
    public ResultDto checkName(@RequestParam String orderNo, @RequestParam String fileName) {
        Boolean result = orderFileService.checkUniqueName(orderNo, fileName);
        ResultDto resultDto = new ResultDto();
        resultDto.setData(result);
        return resultDto;
    }

    /**
     * 新增订单附件
     */
    @ApiOperation(value = "新增订单的附件", notes = "新增订单附件<br>权限：" + Permissions.BIZ_MGT_ORD_ORDER,position = 3)
    @RequestMapping(value = "/{orderNo}/orderFiles", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_ORD_ORDER)
    public ResultDto addOrderFile(@PathVariable String orderNo, @RequestBody @ApiParam(value = "要保存的数据", required = true) @Validated OrdOrderFileDto fileDto) {
        fileDto.setOrderNo(orderNo);
        fileDto.setCreateUserType(CommCodes.OPERATOR_USER_TYPE);
        Integer id = orderFileService.addOrderFileDto(fileDto);
        OrdOrderFileDto returnDto = orderFileService.getByOrderFileId(id);
        ResultDto result = getSaveSuccessDto(MessagesCodes.MODULE_ORDER_FILE);
        result.setData(returnDto);
        return result;
    }

    /**
     * 删除订单附件
     *
     * @return
     */
    @ApiOperation(value = "删除订单的附件", notes = "删除订单附件<br>权限：" + Permissions.BIZ_MGT_ORD_ORDER,position = 4)
    @RequestMapping(value = "/{orderNo}/{orderFileId}/delete", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_ORD_ORDER)
    public ResultDto deleteOrderFile(@PathVariable String orderNo, @PathVariable Integer orderFileId) {
        orderFileService.deleteOrderFile(orderNo, orderFileId, CommCodes.OPERATOR);
        return getDeleteSuccessDto(MessagesCodes.MODULE_ORDER_FILE);
    }


    /**
     * 分页获取某个订单的附件
     */

    @ApiOperation(value = "分页获取某个订单下的附件列表", notes = "分页获取某个订单下的附件列表",position = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query", defaultValue
                    = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数,max<2000", dataType = "int", paramType = "query",
                    defaultValue = "10"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue =
                    "true"),
            @ApiImplicitParam(name = "orderNo", value = "订单号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "q", value = "关键字", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单的状态", dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResultDto find(@RequestParam(required = false) String q,
                          @RequestParam(required = false, defaultValue = "1") int pageIndex,
                          @RequestParam(required = false, defaultValue = "10") int pageSize,
                          @RequestParam String orderNo,
                          @RequestParam(required = false, defaultValue = "") String startTime,
                          @RequestParam(required = false, defaultValue = "") String endTime,
                          @RequestParam(required = false) OrderStatus orderStatus,
                          @RequestParam(required = false) String sort,
                          @RequestParam(required = false, defaultValue = "true") Boolean asc
    ) {
        q = StringUtils.replaceSqlPattern(q);
        QueryParams qp = new QueryParams(pageSize, pageIndex, q, sort, asc);
        qp.put("orderNo", orderNo.trim());

        if (!ObjectUtils.isEmpty(orderStatus)) {
            qp.put("orderStatus", orderStatus);
        }
        try {
            if (!ObjectUtils.isEmpty(startTime)) {
                qp.put("startTime", DateUtils.convertToDate(startTime, DateUtils.FORMAT_DETAIL));
            }
            if (!ObjectUtils.isEmpty(endTime)) {
                qp.put("endTime", DateUtils.convertToDate(endTime, DateUtils.FORMAT_DETAIL));
            }
        } catch (ParseException e) {
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_ILLEGAL, "startTime or endTime ");
        }
        return orderFileService.findFileDtoPages(qp);

    }

}
